//
//  CPNetwork.m
//  News
//
//  Created by chen on 15/3/24.
//  Copyright (c) 2015年 chen. All rights reserved.
//

#import "CPNetwork.h"
// 网络接口怎么去设计：




@interface CPNetwork()
@property (nonatomic, strong) NSURLSession *session;

@end



@implementation CPNetwork

- (NSURLSession *)session{
    if (_session == nil){
        
        _session = [NSURLSession sharedSession];
        
    }
    return  _session;
    
  
}

- (void)requestJSON:(NSString *)baseURLString  httpMethod:(HTTPMethod)method  parameter:(NSDictionary *)parameter completionHandler:(Completion)completionHandler

{
    if (method == HTTPMethodPost){ // method 为post
        NSString *quertyStrign = [self queryString:parameter];
        
        if ( quertyStrign == nil){
            NSError *error = [NSError errorWithDomain:@"user.net" code:-1 userInfo:@{@"post":@"paramer不能为空"}];
            completionHandler(nil, error);
            
            return;
        }
        
    
        NSMutableURLRequest *requestM= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseURLString]];
        
        requestM.HTTPMethod = @"POST";
        NSString *bodyString = [quertyStrign stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        requestM.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        [[self.session dataTaskWithRequest:requestM completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            
            if (error != nil)
            {
                completionHandler(nil,error);
            }
            

            completionHandler(data, error);
            
        }] resume];
        
        
    }else{ // method 为get
    
        NSMutableString *URLString = [baseURLString mutableCopy];
        
        NSString *queryString = [self queryString:parameter];
        if (queryString != nil){
            [URLString appendString:[NSString stringWithFormat:@"?%@",queryString]];
        }
        
        [[self.session dataTaskWithURL:[NSURL URLWithString:URLString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // 数据返回时 回调
          
           if (error != nil)
           {
               completionHandler(nil,error);
           }
            
            completionHandler(data, error);
            
        }] resume];
    }
   
}


// 从 parames 中 得到 字典
- (NSString *)queryString:(NSDictionary *)parames{
    
    if (parames == nil)
    {
        return  nil;
    }
    
    NSMutableString *arrayM = [NSMutableString string];
 
    [parames enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
      
        [arrayM appendString:[NSString stringWithFormat:@"%@=%@&",(NSString *)key,(NSString *)obj]];
        
    }];
    
    
    return [arrayM substringToIndex:arrayM.length-1];
}

@end
